package com.xmx.ndmallwxapi.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.qcloud.cos.utils.StringUtils;
import com.xmx.common.config.WxResponseCode;
import com.xmx.common.utils.ListFromEntity2VoUtils;
import com.xmx.common.utils.MapUtils;
import com.xmx.common.utils.R;
import com.xmx.ndmallwxapi.feign.*;
import com.xmx.ndmallwxapi.vo.cart.CartAddVo;
import com.xmx.ndmallwxapi.vo.copon.CouponAllVo;
import com.xmx.ndmallwxapi.vo.copon.CouponVo;
import com.xmx.ndmallwxapi.vo.goods.GoodDetailVo;
import com.xmx.ndmallwxapi.vo.user.AddressVo;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.xmx.common.config.WxResponseCode.*;


@Service
public class CartService {
    @Resource
    OrderFeignClient orderFeignClient;
    @Resource
    ProductFeignClient productFeignClient;

    @Resource
    UserFeignClient userFeignClient;

    @Resource
    PromotionFeignClient promotionFeignClient;

    @Resource
    CouponFeignClient couponFeignClient;

    public Integer countgood(Integer uid){
        return (Integer) orderFeignClient.count(uid).get("goodscount");
    }


    public R fastadds(Integer userId,CartAddVo cartdata){

        Integer goodsId   =  cartdata.getGoodsId();
        Integer number    = cartdata.getNumber();
        Integer productId =  cartdata.getProductId();

        // TODO:  非空验证
        if(ObjectUtil.isNull(goodsId)&& ObjectUtil.isNull(number)&&ObjectUtil.isNull(productId)){
            return R.error(402,"参数值不对");
        }
        // TODO:  判断商品是否可以购买（是否在售）
        R goodsdetailR =  productFeignClient.info(goodsId);
        List<Map> goodsinfoMap = new ArrayList<>();
        goodsinfoMap.add((Map)goodsdetailR.get("goods"));
        GoodDetailVo goods =  ListFromEntity2VoUtils.entity2Vo(goodsinfoMap, GoodDetailVo.class).get(0);
        if(goods==null|| !goods.getIsOnSale()){
            return R.error(GOODS_UNSHELVE.getCode(),GOODS_UNSHELVE.getMsg());
        }


        Map product = (Map) productFeignClient.goodsproductinfo(productId).get("goodsProduct");
        // TODO:  判断购物车中是否存在此规格商品

        R queryExist = orderFeignClient.queryExist(goodsId, productId, userId);
        CartAddVo existcart = null;
        Integer newIdforcart = null;
        if(queryExist.get("data")==null){

            // TODO:  取得规格的信息,判断规格库存
            if (product == null || number > (Integer) product.get("number")) {
                return R.error(GOODS_NO_STOCK.getCode(), GOODS_NO_STOCK.getMsg());
            }
            cartdata.setId(null);
            cartdata.setGoodsSn(goods.getGoodsSn());
            cartdata.setGoodsName(goods.getName());
            if(StringUtils.isNullOrEmpty((String) product.get("picUrl")))
                cartdata.setPicUrl(goods.getPicUrl());
            else
                cartdata.setPicUrl((String) product.get("picUrl"));
            cartdata.setPrice(new BigDecimal(String.valueOf( product.get("price"))));

            cartdata.setSpecifications(JSONUtil.parseArray((String) product.get("specifications")).toArray(new String[]{}));
            cartdata.setUserId(userId);
            cartdata.setChecked(true);

            //添加到购物车
             newIdforcart = (Integer) orderFeignClient.saveCart(cartdata).get("data");
        }else {
            List<Map> cartexformap = new ArrayList<>();
            cartexformap.add((Map)queryExist.get("data"));
//              existcart =  ListFromEntity2VoUtils.entity2Vo(cartexformap, CartAddVo.class).get(0);
              existcart = BeanUtil.mapToBean((Map)queryExist.get("data"),CartAddVo.class,true);
            int num = number;
            if(num>(Integer) product.get("number")){
                return R.error(GOODS_NO_STOCK.getCode(),GOODS_NO_STOCK.getMsg());
            }
            existcart.setNumber(number);

            Map a = BeanUtil.beanToMap(existcart);
            System.out.println(a);
            a.replace("specifications",a.get("specifications"),JSONUtil.toJsonStr(existcart.getSpecifications()));

            if((Integer) orderFeignClient.updateCart(a).get("errno")!=0){
                return R.error("更新失败");
            }


        }
        // TODO:  返回购物车id
        return R.ok().put("data",existcart==null?newIdforcart:existcart.getId());
    }


    /**
     * 将购物车中的商品checkout
     */
    public R checkout(Integer userId, Integer cartId, Integer addressId, Integer couponId, Integer userCouponId, Integer grouponRulesId){
        // TODO:  判断是否登录

        // TODO:  获取收货地址

        AddressVo addressVo = null;
        if(addressId == null || addressId.equals(0)){
            R addressR = userFeignClient.findlistByDefault(userId);
            if(ObjectUtils.isEmpty(addressR.get("data"))) {
                addressVo = new AddressVo();
                addressVo.setId(0);
            }else {
                List<Map> addressList = new ArrayList<>();
                addressList.add((Map)addressR.get("data"));
                 addressVo = ListFromEntity2VoUtils.entity2Vo(addressList, AddressVo.class).get(0);
                 addressId = addressVo.getId();
            }
        }else {
            R addrR = userFeignClient.findlistByuid(userId, addressId);
            List<Map> addressList = new ArrayList<>();
            addressList.add((Map)addrR.get("data"));
            if(ObjectUtils.isEmpty(addrR.get("data"))){
                return R.error("空参数的！");
            }
            addressVo = ListFromEntity2VoUtils.entity2Vo(addressList, AddressVo.class).get(0);
        }
        // TODO:  获取团购信息
        BigDecimal grouponPrice = new BigDecimal(0.00);
        R grouponRuleR = promotionFeignClient.getdetailByid(grouponRulesId);
        // 获取团购价格
        if(!ObjectUtils.isEmpty(grouponRuleR.get("grouponRules"))){
            Map map = (Map) grouponRuleR.get("grouponRules");
             grouponPrice = new BigDecimal(String.valueOf(map.get("discount")));
        }
        // TODO:  是否选中购物车,将查询出来的商品存放在购物车集合中
        List<CartAddVo> cartAddVoList = new ArrayList<>();
            if(cartId!=null || cartId!=0){
                R cartR = orderFeignClient.infoCart(cartId);

                CartAddVo cartAddVo = null;
                if(!ObjectUtils.isEmpty(cartR.get("cart"))){

                    cartAddVoList.add( BeanUtil.mapToBean((Map) cartR.get("cart"),CartAddVo.class,false));

                    for (int i = 0; i < cartAddVoList.size(); i++) {

                        String specification = cartAddVoList.get(i).getSpecifications()[0];

                        cartAddVoList.get(i).setSpecifications(JSONUtil.parseArray(specification).toArray(new String[]{}));
                    }

                }else {
                    return R.error("购物车为空！！");
                }

            }else{
                // TODO:  处理从购物车中挑选出来的商品（未处理
                cartAddVoList = null;
            }

            // TODO:  处理团购价格 （计算商品价格
         BigDecimal checkedGoodsPrice = new BigDecimal(0.00);
        //从购物车中取出商品信息获取其价格
        for (CartAddVo cart : cartAddVoList) {
            if(cart==null)
                return R.error("购物车为空");
            if(!ObjectUtils.isEmpty(grouponRuleR.get("grouponRules")) && ((Map)grouponRuleR.get("grouponRules")).get("goodsId").equals(cart.getGoodsId())){
                    checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().subtract(grouponPrice).multiply(new BigDecimal(cart.getNumber())));
            }else {
                checkedGoodsPrice = checkedGoodsPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
            }
        }
//       // TODO:  获取优惠券信息列表(用户优惠券、系统门槛优惠券)
        //先获取用户优惠券（用户自带的）
        //查一个无门槛的
        //暂存数据，优惠券金额
        BigDecimal tmpCouponPrice = new BigDecimal(0.00);
        //优惠券的id
        Integer tmpCouponId = 0;
        //用户优惠券表的id
        Integer tmpUserCouponId = 0;
        //优惠券数量
        int tmpCouponLength = 0;
        List<Map> couponMap = (List<Map>) couponFeignClient.getlistbyuid(userId).get("data");
        for (Map cmap : couponMap) {
            //判断可用的优惠券id
            tmpCouponId = (Integer) cmap.get("couponId");
            CouponAllVo coupon = checkCoupon(tmpCouponId, (Integer) cmap.get("id"), checkedGoodsPrice, cartAddVoList);
            if(coupon == null){
                continue;
            }
            tmpCouponLength++;
            if(tmpCouponPrice.compareTo(coupon.getDiscount()) == -1){
                tmpCouponPrice = coupon.getDiscount();
                tmpCouponId = coupon.getId();
                tmpUserCouponId = (Integer) cmap.get("id");
            }
        }
        //获取选中的

        int availableCouponLength = tmpCouponLength;
        BigDecimal couponPrice = new BigDecimal(0);
        if (couponId == null || couponId.equals(-1)){
            couponId = -1;
            userCouponId = -1;
        }
        else if (couponId.equals(0)) {
            couponPrice = tmpCouponPrice;
            couponId = tmpCouponId;
            userCouponId = tmpUserCouponId;
        }else {
            CouponAllVo coupon = checkCoupon( couponId, userCouponId, checkedGoodsPrice, cartAddVoList);
            // 用户选择的优惠券有问题，则选择合适优惠券，否则使用用户选择的优惠券
            if(coupon == null){
                couponPrice = tmpCouponPrice;
                couponId = tmpCouponId;
                userCouponId = tmpUserCouponId;
            }
            else {
                couponPrice = coupon.getDiscount();
            }
        }

        // 根据订单商品总价计算运费，满88则免运费，否则8元；
        BigDecimal freightPrice = new BigDecimal(0.00);
        if (checkedGoodsPrice.compareTo(new BigDecimal(88)) < 0) {
            freightPrice = new BigDecimal(8);
        }

        // 可以使用的其他钱，例如用户积分
        BigDecimal integralPrice = new BigDecimal(0.00);

        // 订单费用
        BigDecimal orderTotalPrice = checkedGoodsPrice.add(freightPrice).subtract(couponPrice).max(new BigDecimal(0.00));

        BigDecimal actualPrice = orderTotalPrice.subtract(integralPrice);

        Map<String, Object> data = new HashMap<>();
        data.put("addressId", addressId);
        data.put("couponId", couponId);
        data.put("userCouponId", userCouponId);
        data.put("cartId", cartId);
        data.put("grouponRulesId", grouponRulesId);
        data.put("grouponPrice", grouponPrice);
        data.put("checkedAddress", addressVo);
        data.put("availableCouponLength", availableCouponLength);
        data.put("goodsTotalPrice", checkedGoodsPrice);
        data.put("freightPrice", freightPrice);
        data.put("couponPrice", couponPrice);
        data.put("orderTotalPrice", orderTotalPrice);
        data.put("actualPrice", actualPrice);
        data.put("checkedGoodsList", cartAddVoList);

        // TODO:  判断库存是否充足
        return R.ok().put("data",data);
    }


    /**
     * 判断优惠券是否合适
     * @param couponId
     * @param userCouponId
     * @param checkedGoodsPrice
     * @param cartListi
     * @return
     */
    public CouponAllVo checkCoupon( Integer couponId, Integer userCouponId, BigDecimal checkedGoodsPrice, List<CartAddVo> cartListi){
        R infocoupon = couponFeignClient.infocoupon(couponId);
        CouponAllVo couponAllVo = BeanUtil.mapToBean((Map) infocoupon.get("coupon"), CouponAllVo.class,true);
        if(couponAllVo == null)
            return null;
        Map couponUser = (Map) couponFeignClient.infoUsercoupon(userCouponId).get("couponUser");
        //如果找不到
        if(couponUser == null) {
            return null;
        }else if(!couponId.equals(couponUser.get("couponId"))){
            return null;
        }

        // 检查是否超期

        LocalDateTime now = LocalDateTime.now();
        if(couponAllVo.getTimeType()==1){
            if(now.isBefore(couponAllVo.getStartTime())|| now.isAfter(couponAllVo.getEndTime())){
                return null;
            }
        }else if(couponAllVo.getTimeType()==0){

            LocalDateTime exprired = LocalDateTime.parse((String)couponUser.get("addTime")).plusDays(couponAllVo.getDays());
            if(now.isAfter(exprired)){
                return null;
            }
        }
        else {
            return null;
        }

        //检测商品是否符合标准
        if(couponAllVo.getGoodsType().equals(1) || couponAllVo.getGoodsType().equals(2)){
            for (CartAddVo cartAddVo : cartListi) {
                Integer key = couponAllVo.getGoodsType().equals(1)? cartAddVo.getGoodsId():0;
            }
        }

        // 检测订单状态

        if (!couponAllVo.getStatus().equals(0)) {
            return null;
        }
        // 检测是否满足最低消费
        if (checkedGoodsPrice.compareTo(couponAllVo.getMin()) == -1) {
            return null;
        }
        return couponAllVo;
    }

}
